package com.tataben.db.util;

import com.tataben.db.DLLogger;
import com.tataben.db.annotation.Column;
import com.tataben.db.converter.DLCCFactory;
import com.tataben.db.table.DLColumn;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.LinkedHashMap;

public final class DLTableUtils {

    private DLTableUtils() {}

    /**
     * 获取表中所有列
     * @param entityType
     * @return
     */
    public static synchronized LinkedHashMap<String, DLColumn> findColumnMap(Class<?> entityType) {
        LinkedHashMap<String, DLColumn> columnMap = new LinkedHashMap<>();
        addColumns2Map(entityType, columnMap);
        return columnMap;
    }

    /**
     * 递归遍历表中列
     * @param entityType
     * @param columnMap
     */
    private static void addColumns2Map(Class<?> entityType, HashMap<String, DLColumn> columnMap) {
        if (Object.class.equals(entityType)) return;
        try {
            Field[] fields = entityType.getDeclaredFields();
            for (Field field : fields) {
                int modify = field.getModifiers();
                if (Modifier.isStatic(modify) || Modifier.isTransient(modify)) {
                    continue;
                }
                Column columnAnn = field.getAnnotation(Column.class);
                if (columnAnn != null) {
                    if (DLCCFactory.isSupportColumnConverter(field.getType())) {
                        DLColumn column = new DLColumn(entityType, field, columnAnn);
                        if (!columnMap.containsKey(column.getName())) {
                            columnMap.put(column.getName(), column);
                        }
                    }
                }
            }
            addColumns2Map(entityType.getSuperclass(), columnMap);
        } catch (Throwable e) {
            DLLogger.e(e.getMessage(), e);
        }
    }
}